//
//  JSBridgeUI.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/2/9.
//  Copyright © 2020 com.example. All rights reserved.
//

import Foundation
import UIKit

class JSBridgeUI : BridgeModuelBase {
    
    // 1. 使用weak解除循环引用问题
    weak var viewController: WebViewController?
    
    init(viewController: WebViewController) {
        self.viewController = viewController
    }
    
    override func callFunc(_ funcName: String, callbackId: String, arg: [String : Any?]) {
        switch funcName {
        case "toast":
            toast(arg)
        case "alert":
            alert(arg)
        case "confirm":
            confirm(callbackId: callbackId, arg)
        default: break
        }
    }
    
    func toast(_ arg: [String : Any?]) {
        guard let message = arg["message"] as? String else {
            return
        }
        viewController?.view.makeToast(message)
    }
    
    func alert(_ arg: [String : Any?]) {
        let title = arg["title"] as? String ?? "提示"
        let message = arg["message"] as? String ?? ""
        let button = arg["button"] as? String ?? "确定"
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: button, style: .default, handler: {
            action in
            
        })
        alertController.addAction(okAction)
        viewController?.present(alertController, animated: true, completion: nil)
    }
    
    func confirm(callbackId: String, _ arg: [String : Any?]) {
        let title = arg["title"] as? String ?? "提示"
        let message = arg["message"] as? String ?? ""
        let buttons = arg["buttons"] as? [String] ?? ["取消", "确定"]
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        buttons.forEach { button in
            let action = UIAlertAction(title: button, style: .default) { action in
                self.callback(callbackId: callbackId, value: buttons.firstIndex(of: button)!)
            }
            alertController.addAction(action)
        }
        
        viewController?.present(alertController, animated: true, completion: nil)
    }
}
